package ru.ifmo.tanya.service;

import org.jdom.Element;
import org.jdom.transform.XSLTransformException;
import ru.ifmo.tanya.core.users.User;
import ru.ifmo.tanya.util.StreamUtil;
import ru.ifmo.tanya.xml.SaxonXmlProcessor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


public abstract class XmlService extends AuthorizedHttpService {

    private final SaxonXmlProcessor xmlProcessor = new SaxonXmlProcessor();

    @Override
    public void invokeWithUser(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Element xmlResponse = new Element("response");
        invoke(user, request, xmlResponse);
        try {
            InputStream xslStream = getClass().getResourceAsStream(getXslFilePath());
            StreamUtil.printToStream(xmlProcessor.process(xmlResponse, xslStream), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public abstract void invoke(User user, HttpServletRequest request, Element response);

    public abstract String getXslFilePath();
}
